import dayjs from 'dayjs'
import { OrderStatus, OrderType, PaymentMethod, type Order, type OrderListParams } from '../api/orders'

// 生成随机日期
function randomDate(start: Date, end: Date): Date {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
}

// 格式化日期
function formatDate(date: Date): string {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 生成随机订单号
function generateOrderNo(): string {
  const timestamp = dayjs().format('YYYYMMDDHHmmss')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  return `ORD${timestamp}${random}`
}

// 模拟订单数据
export const orders: Order[] = [
  // 门票订单
  {
    id: '1',
    orderNo: 'ORD20240501000001',
    userId: '101',
    userName: '张三',
    userPhone: '13800138001',
    orderType: OrderType.TICKET,
    orderStatus: OrderStatus.COMPLETED,
    productId: '201',
    productName: '丹寨万达小镇门票',
    productQuantity: 2,
    unitPrice: 80,
    totalAmount: 160,
    discountAmount: 20,
    paymentAmount: 140,
    paymentMethod: PaymentMethod.WECHAT,
    paymentTime: '2024-05-01 09:15:23',
    remark: '家庭游',
    createTime: '2024-05-01 09:10:05',
    updateTime: '2024-05-01 15:30:20',
    contactName: '张三',
    contactPhone: '13800138001',
    useDate: '2024-05-03',
    useTime: '09:00-18:00',
    guests: [
      {
        name: '张三',
        idType: '身份证',
        idNumber: '110101199001011234',
        phone: '13800138001'
      },
      {
        name: '李四',
        idType: '身份证',
        idNumber: '110101199002022345',
        phone: '13800138002'
      }
    ]
  },
  // 酒店订单
  {
    id: '2',
    orderNo: 'ORD20240502000002',
    userId: '102',
    userName: '李四',
    userPhone: '13900139001',
    orderType: OrderType.HOTEL,
    orderStatus: OrderStatus.CONFIRMED,
    productId: '301',
    productName: '森林温泉酒店-豪华双床房',
    productQuantity: 1,
    unitPrice: 580,
    totalAmount: 580,
    discountAmount: 0,
    paymentAmount: 580,
    paymentMethod: PaymentMethod.ALIPAY,
    paymentTime: '2024-05-02 14:25:33',
    createTime: '2024-05-02 14:20:15',
    updateTime: '2024-05-02 16:10:22',
    contactName: '李四',
    contactPhone: '13900139001',
    checkInDate: '2024-05-15',
    checkOutDate: '2024-05-17',
    roomType: '豪华双床房',
    roomCount: 1
  },
  // 活动订单
  {
    id: '3',
    orderNo: 'ORD20240503000003',
    userId: '103',
    userName: '王五',
    userPhone: '13700137001',
    orderType: OrderType.ACTIVITY,
    orderStatus: OrderStatus.PAID,
    productId: '401',
    productName: '贵州民族文化体验活动',
    productQuantity: 3,
    unitPrice: 120,
    totalAmount: 360,
    discountAmount: 60,
    paymentAmount: 300,
    paymentMethod: PaymentMethod.WECHAT,
    paymentTime: '2024-05-03 10:05:42',
    createTime: '2024-05-03 10:01:18',
    updateTime: '2024-05-03 10:05:42',
    contactName: '王五',
    contactPhone: '13700137001',
    useDate: '2024-06-10',
    useTime: '14:00-17:00',
    guests: [
      {
        name: '王五',
        idType: '身份证',
        idNumber: '110101199003033456',
        phone: '13700137001'
      },
      {
        name: '赵六',
        idType: '身份证',
        idNumber: '110101199004044567',
        phone: '13700137002'
      },
      {
        name: '钱七',
        idType: '身份证',
        idNumber: '110101199005055678',
        phone: '13700137003'
      }
    ]
  },
  // 套餐订单
  {
    id: '4',
    orderNo: 'ORD20240504000004',
    userId: '104',
    userName: '赵六',
    userPhone: '13600136001',
    orderType: OrderType.PACKAGE,
    orderStatus: OrderStatus.PENDING,
    productId: '501',
    productName: '贵州三日游套餐',
    productQuantity: 2,
    unitPrice: 1500,
    totalAmount: 3000,
    discountAmount: 300,
    paymentAmount: 2700,
    createTime: '2024-05-04 16:30:25',
    contactName: '赵六',
    contactPhone: '13600136001',
    useDate: '2024-07-01',
    remark: '需要接站服务'
  },
  // 已取消订单
  {
    id: '5',
    orderNo: 'ORD20240505000005',
    userId: '105',
    userName: '孙七',
    userPhone: '13500135001',
    orderType: OrderType.TICKET,
    orderStatus: OrderStatus.CANCELLED,
    productId: '202',
    productName: '黄果树瀑布门票',
    productQuantity: 4,
    unitPrice: 100,
    totalAmount: 400,
    discountAmount: 40,
    paymentAmount: 360,
    paymentMethod: PaymentMethod.ALIPAY,
    paymentTime: '2024-05-05 09:05:33',
    createTime: '2024-05-05 09:01:25',
    updateTime: '2024-05-05 15:20:42',
    contactName: '孙七',
    contactPhone: '13500135001',
    useDate: '2024-05-10',
    useTime: '08:00-17:00',
    cancelReason: '行程变更'
  },
  // 退款订单
  {
    id: '6',
    orderNo: 'ORD20240506000006',
    userId: '106',
    userName: '周八',
    userPhone: '13400134001',
    orderType: OrderType.HOTEL,
    orderStatus: OrderStatus.REFUNDED,
    productId: '302',
    productName: '贵阳花溪温泉酒店-标准房',
    productQuantity: 1,
    unitPrice: 480,
    totalAmount: 480,
    discountAmount: 50,
    paymentAmount: 430,
    paymentMethod: PaymentMethod.WECHAT,
    paymentTime: '2024-05-06 11:35:18',
    createTime: '2024-05-06 11:30:05',
    updateTime: '2024-05-07 10:20:15',
    contactName: '周八',
    contactPhone: '13400134001',
    checkInDate: '2024-05-20',
    checkOutDate: '2024-05-22',
    roomType: '标准房',
    roomCount: 1,
    refundAmount: 430,
    refundTime: '2024-05-07 10:20:15',
    refundReason: '行程取消'
  }
]

// 根据查询条件筛选订单
export function filterOrders(params: OrderListParams) {
  let filteredOrders = [...orders]
  
  // 关键词搜索
  if (params.keyword) {
    const keyword = params.keyword.toLowerCase()
    filteredOrders = filteredOrders.filter(
      order => order.orderNo.toLowerCase().includes(keyword) || 
               order.userName.toLowerCase().includes(keyword) ||
               order.userPhone.includes(keyword) ||
               order.productName.toLowerCase().includes(keyword)
    )
  }
  
  // 订单类型筛选
  if (params.orderType) {
    filteredOrders = filteredOrders.filter(order => order.orderType === params.orderType)
  }
  
  // 订单状态筛选
  if (params.orderStatus) {
    filteredOrders = filteredOrders.filter(order => order.orderStatus === params.orderStatus)
  }
  
  // 日期范围筛选
  if (params.startDate) {
    const startDate = dayjs(params.startDate).startOf('day')
    filteredOrders = filteredOrders.filter(order => dayjs(order.createTime).isAfter(startDate) || dayjs(order.createTime).isSame(startDate))
  }
  
  if (params.endDate) {
    const endDate = dayjs(params.endDate).endOf('day')
    filteredOrders = filteredOrders.filter(order => dayjs(order.createTime).isBefore(endDate) || dayjs(order.createTime).isSame(endDate))
  }
  
  // 计算总数
  const total = filteredOrders.length
  
  // 排序 - 默认按创建时间降序
  filteredOrders.sort((a, b) => {
    return dayjs(b.createTime).valueOf() - dayjs(a.createTime).valueOf()
  })
  
  // 分页
  const page = Number(params.page) || 1
  const pageSize = Number(params.pageSize) || 10
  const start = (page - 1) * pageSize
  const end = start + pageSize
  
  // 提取分页数据
  const pageData = filteredOrders.slice(start, end)
  
  return {
    list: pageData,
    total,
    page,
    pageSize
  }
}

// 根据ID获取订单
export function getOrderById(id: string): Order | undefined {
  return orders.find(order => order.id === id)
}

// 更新订单状态
export function updateOrderStatusById(id: string, status: OrderStatus, reason?: string): Order | undefined {
  const index = orders.findIndex(order => order.id === id)
  if (index !== -1) {
    orders[index].orderStatus = status
    orders[index].updateTime = formatDate(new Date())
    
    // 处理特殊状态
    if (status === OrderStatus.CANCELLED) {
      orders[index].cancelReason = reason
    }
    
    return orders[index]
  }
  return undefined
}

// 处理退款
export function handleRefund(id: string, reason: string, amount: number): Order | undefined {
  const index = orders.findIndex(order => order.id === id)
  if (index !== -1) {
    orders[index].orderStatus = OrderStatus.REFUNDING
    orders[index].refundReason = reason
    orders[index].refundAmount = amount
    orders[index].updateTime = formatDate(new Date())
    return orders[index]
  }
  return undefined
}

// 确认退款
export function completeRefund(id: string): Order | undefined {
  const index = orders.findIndex(order => order.id === id)
  if (index !== -1) {
    orders[index].orderStatus = OrderStatus.REFUNDED
    orders[index].refundTime = formatDate(new Date())
    orders[index].updateTime = formatDate(new Date())
    return orders[index]
  }
  return undefined
}

// 更新订单备注
export function updateOrderRemarkById(id: string, remark: string): Order | undefined {
  const index = orders.findIndex(order => order.id === id)
  if (index !== -1) {
    orders[index].remark = remark
    orders[index].updateTime = formatDate(new Date())
    return orders[index]
  }
  return undefined
} 